package org.example.fact;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@BenchmarkMode({Mode.AverageTime, Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
//@State(Scope.Thread)


public class FactJSONBenchmark {

    private static final String json = "{\"connectTimeout\":false,\"readTimeout\":false,\"subCode\":0,\"subMsg\":\"成功\",\"pid\":300083,\"improveTime\":1728385794000,\"improveAmount\":33000,\"originalAmount\":30000,\"businessSuccess\":true,\"timeout\":false,\"success\":true}";

    @Benchmark
    public void eachJSONPath() {
        Fact fact = new Fact();
        fact.setFactData("content", json);

        String subMsg = JSONContentToStringConverter.convert("subMsg", fact);
        Preconditions.checkArgument(subMsg.equals("成功"));

        String originalAmount = JSONContentToStringConverter.convert("originalAmount", fact);
        Preconditions.checkArgument(originalAmount.equals("30000"));

        String improveTime = JSONContentToStringConverter.convert("improveTime", fact);
        Preconditions.checkArgument(improveTime.equals("1728385794000"));
    }

    @Benchmark
    public void stringBuilder() {
        Fact fact = new Fact();
        fact.setFactData("content", json);

        JSONObject jsonObject = JSON.parseObject(json);
        fact.pullAllFactData(jsonObject);

        Object subMsg = fact.getFactData("subMsg");
        Preconditions.checkArgument(subMsg.equals("成功"));

        Object originalAmount = fact.getFactData("originalAmount");
        Preconditions.checkArgument(originalAmount.equals(30000));

        Object improveTime = fact.getFactData("improveTime");
        Preconditions.checkArgument(improveTime.equals(1728385794000L));
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(FactJSONBenchmark.class.getSimpleName())
//            .timeUnit(TimeUnit.MICROSECONDS)
                .build();

        new Runner(opt).run();
    }
}